import { Form, Input, Modal, notification } from 'antd';

import { usePost } from '@/api';
import { IconsMap } from '@/components/complex/IconsMap';

interface CategoryAddProps extends HTMLElementProps {
  type: 'add' | 'edit';
  refresh: (category: { id: number; name: string }) => void;
}

export interface CategoryModifyFormRef {
  setVisible: (visible: boolean) => void;
  setFormValue: (data: { name: string; icon: string; categoryId: number }) => void;
}

export const CategoryModifyForm = memo(
  forwardRef<CategoryModifyFormRef, CategoryAddProps>((props, ref) => {
    const [visible, setVisible] = useState(false);
    const categoryIdRef = useRef<number>(0);
    const [form] = Form.useForm();
    const { loading: addLoading, runAsync: categoryAdd } = usePost('/category/add', {}, { manual: true });
    const { loading: renameLoading, runAsync: categoryRename } = usePost('/category/rename', {}, { manual: true });
    const loading = addLoading || renameLoading;

    const submit = () => {
      form.validateFields().then((values) => {
        if (props.type === 'edit') {
          if (!categoryIdRef.current) {
            notification.error({ message: 'categoryId 不能为空' });
            return;
          }
          categoryRename({
            categoryId: categoryIdRef.current,
            ...values
          }).then(() => {
            setVisible(false);
            notification.success({ message: '操作成功' });
            props.refresh(values);
            form.resetFields();
          });
          return;
        }
        categoryAdd({
          ...values
        } as never).then((id) => {
          setVisible(false);
          notification.success({ message: '操作成功' });
          props.refresh({ id, name: values.name });
          form.resetFields();
        });
      });
    };

    const setFormValue: CategoryModifyFormRef['setFormValue'] = (data) => {
      categoryIdRef.current = data.categoryId;
      form.setFieldsValue(data);
    };

    useImperativeHandle(ref, () => ({
      setVisible,
      setFormValue
    }));

    return (
      <>
        {props.children && (
          <div className="category-modify-form" onClick={() => setVisible(true)}>
            {props.children}
          </div>
        )}

        <Modal
          title={props.type === 'add' ? '新增场景' : '编辑场景'}
          open={visible}
          onOk={submit}
          destroyOnClose
          confirmLoading={loading}
          onCancel={() => setVisible(false)}>
          <Form form={form}>
            <Form.Item label="决策名称" name="name" rules={[{ required: true }]}>
              <Input maxLength={20} />
            </Form.Item>
            <Form.Item label="图标" name="icon" rules={[{ required: true, message: '请选择图标' }]}>
              <IconsMap className="h-200 overflow-y-auto" />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  })
);
